from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from rest_framework.response import Response
from rest_framework.request import HttpRequest
from django.conf import settings
from rest_framework import status
from jwt import encode
from .models import User
from .serializers import *
from apps.user.models import UnderGroups
from .filters import *
from rest_framework.decorators import action
from apps.devices.serializers import DevicesModelSerializer
from apps.devices.models import Devices


class LoginView(APIView):
    permission_classes = []
    authentication_classes = []

    def post(self, request:HttpRequest, version):
        '''
        用户登录  签发jwt  token
        :param request:
        :param version:
        :return:
        '''
        ua = request.headers.get("User-Agent","")
        is_wechat = ua.find("MicroMessenger") >= 0 
        
        code = request.session.get('code')
        form_code = request.data.get('code')
        if not is_wechat:
            if not request.data.get('code') or not code:
                return Response(
                    {
                        'code': '403',
                        'msg': '验证码错误'
                    }
                )
            else:
                form_code = request.data.get('code')

                if form_code.upper() != code.upper():
                    return Response(
                        {
                            'code': '403',
                            'msg': '验证码错误'
                        }
                    )
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        if user and user.check_password(password):
            user_serializers = UserModelSerializers(instance=user)
            # user_serializers.is_valid()
            return Response({
                'code': status.HTTP_200_OK,
                'msg': '登录成功',
                'token': encode(dict(user_serializers.data), key=settings.SECRET_KEY)
            })
        else:
            return Response(
                {
                    'code': '403',
                    'msg': '用户名密码错误'
                }
            )


class UserInfoView(APIView):

    def get(self, request, version):
        user: User = request.user
        print(User)
        data = UserInfoModelSerializers(instance=user)
        return Response(data.data)


class UserManageView(ModelViewSet):

    queryset = User.objects.all()
    filter_class = UserListFilter
    serializer_class = UserListSerializers

    def filter_queryset(self, queryset):

        queryset = super().filter_queryset(queryset)
        print(self.request.user.is_superuser)
        if self.request.user.is_superuser:
            return queryset

        return queryset.filter(parent_user_id=self.request.user.id).all()

    def update(self, request, *args, **kwargs):
        obj = self.get_object()

        if request.user.is_superuser:
            return super().update(request, *args, **kwargs)
        if obj.parent_user and obj.parent_user.id != request.user.id:
            return Response({'code': 200, 'msg': '修改失败'}, 403)

        return Response({'code': 200, 'msg': '修改失败'}, 403)

    def destroy(self, request, *args, **kwargs):
        if self.get_object().id != request.user.id:
            pass
            return super().destroy(request, *args, **kwargs)
        else:
            return Response({
                'msg': '不允许的操作'
            }, 400)

    @action(methods=['get', 'put'], detail=True, url_path='devices', url_name='password')
    def user_devices(self, reqeust, *args, **kwargs):
        if reqeust.method == 'GET':
            user = self.get_object()
            devices = user.devices_set.all()
            devs = DevicesModelSerializer(
                instance=devices, many=True, context={'request': reqeust})
            return Response(devs.data)
        else:
            user = self.get_object()
            update_devices_id = self.request.data.get('ids', [])
            devices = Devices.objects.filter(id__in=update_devices_id).all()
            print(devices)
            user.devices_set.clear()
            user.devices_set.add(*devices)
            return Response({
                'code': 200,
                'msg': '修改成功'
            })

    @action(methods=['put'], detail=True, url_path='password', url_name='password')
    def change_password(self, reqeust, *args, **kwargs):

        user: User = self.get_object()
        password = reqeust.data.get('password')
        user.set_password(password)
        user.save()
        return Response({
            'code': 200,
            'msg': '修改成功'
        })


class GroupView(ModelViewSet):

    queryset = Group.objects.all()
    serializer_class = GroupModelSerializers
    pagination_class = None

    def update(self, request, *args, **kwargs):

        if request.user.is_superuser:
            return super().update(request, *args, **kwargs)
        return Response({"detail": '无权限'}, status.HTTP_403_FORBIDDEN)

    def create(self, request, *args, **kwargs):
        if request.user.is_superuser:
            return super().create(request, *args, **kwargs)
        return Response({"detail": '无权限'}, status.HTTP_403_FORBIDDEN)

    def destroy(self, request, *args, **kwargs):

        if request.user.is_superuser:
            return super().destroy(request, *args, **kwargs)
        return Response({"detail": '无权限'}, status.HTTP_403_FORBIDDEN)


class PermissionView(ReadOnlyModelViewSet):

    queryset = Permission.objects.all()
    serializer_class = PermissionSerializers
    pagination_class = None


class WebSettingView(APIView):

    def get(self, request, *args, **kwargs):
        user: User = request.user
        while  user:
            setting = WebSiteSetting.objects.filter(user_id=user.id).first()
            if setting and setting.logo:
                return Response({
                    'logo': setting.logo,
                    'name': setting.name
                })
            user = user.parent_user

        else:
            return Response({
                'logo': '',
                'name': ''
            })

    def patch(self, request, *args, **kwargs):

      
        setting: WebSiteSetting = WebSiteSetting.objects.filter(user_id=request.user.id).first()
        if setting:
            setting.logo = request.data.get('logo', '')
            setting.name = request.data.get('name', '')
            setting.save()

        else:
            WebSiteSetting.objects.create(user_id=request.user.id,**request.data)

        return Response({
            'code': 200,
            'msg': '修改成功'
        })
